<template>
  <div class="chartBox" :id="id"></div>
</template>
<script>
import * as echarts from 'echarts';

export default {
  name: 'VueECharts',
  props: {
    id: {
      type: String,
      require: true
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    options: {
      immediate: true,
      handler(newVal) {
        this.$nextTick(() => {
          if (this.ready) {
            this.draw && this.draw(newVal);
          }
        });
      }
    }
  },
  mounted() {
    this.ready = true;
  },
  beforeDestroy() {
    this.ready = false;
    this.disponse();
  },
  data() {
    return {
      ready: false,
      chart: null
    };
  },
  methods: {
    init() {
      // 初始化echarts实例
      if (this.chart != null) {
        this.disponse();
      }
      this.chart = echarts.init(document.getElementById(this.id));
    },
    draw(options) {
      // 绘制图表
      this.init();
      this.chart.setOption(options);
      window.addEventListener('resize', this.resizeFn);
    },
    disponse() {
      if (this.chart) {
        window.removeEventListener('resize', this.resizeFn);
        this.chart.dispose();
      }
    },
    resizeFn() {
      this.$nextTick(() => {
        this.chart.resize();
      });
    }
  }
};
</script>

<style lang="less" scoped>
  .chartBox{
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    &>div {
      height: 100%!important;
      &>canvas {
        height: 100%!important;
      }
    }
  }
</style>